import * as THREE from "three";

const createLine = (type) => {
	const points = [
		new THREE.Vector3(0, 0, 0),
		type === "x" ? new THREE.Vector3(100, 0, 0) : new THREE.Vector3(0, 100, 0),
	];
	const geometry = new THREE.BufferGeometry().setFromPoints(points);
	const material = new THREE.LineBasicMaterial({ color: 0xffffff });
	return new THREE.Line(geometry, material);
};

function createScaleLine(type) {
	const points = [];
	for (let i = 0; i <= 100; i += 10) {
		if (type === "y") {
			points.push(new THREE.Vector3(0, i, 0));
			points.push(new THREE.Vector3(-5, i, 0));
		} else {
			points.push(new THREE.Vector3(i, 0, 0));
			points.push(new THREE.Vector3(i, -5, 0));
		}
	}
	const geometry = new THREE.BufferGeometry();
	geometry.setFromPoints(points);
	const material = new THREE.LineBasicMaterial({
		color: "#ffffff",
	});
	const scaleLine = new THREE.LineSegments(geometry, material);
	return scaleLine;
}

function createBar(dataArr) {
	const bars = new THREE.Group();
	dataArr.forEach((item, i) => {
		const geometry = new THREE.PlaneGeometry(10, item, 1, 20);

		const positions = geometry.attributes.position;
		const height = 100;

		const colorsArr = [];
		const color1 = new THREE.Color("red");
		const color2 = new THREE.Color("blue");
		for (let i = 0; i < positions.count; i++) {
			const percent = (positions.getY(i) + item / 2) / height;
			const c = color1.clone().lerp(color2, percent);
			colorsArr.push(c.r, c.g, c.b);
		}
		const colors = new Float32Array(colorsArr);
		geometry.attributes.color = new THREE.BufferAttribute(colors, 3);

		const material = new THREE.MeshBasicMaterial({
			// color: 'orange'
			vertexColors: true,
		});

		const bar = new THREE.Mesh(geometry, material);
		bar.position.x = 10 + i * 20 + 5;
		bar.position.y = item / 2;
		bars.add(bar);
	});
	return bars;
}

const group = new THREE.Group();
group.add(createLine("x"));
group.add(createLine("y"));
group.add(createScaleLine("x"));
group.add(createScaleLine("y"));
group.add(createBar([70, 20, 80, 40, 50]));

export { group };
